package com.ssps.front.tenant2.service2.impl2;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssps.entity.*;
import com.ssps.front.tenant2.service2.Tenant2Service;
import com.ssps.front.tenant2.utils2.Tenant2Utils;
import com.ssps.mapper.*;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: peng
 */
@Transactional
@Service
public class Tenant2ServiceImpl implements Tenant2Service {
    private static String Url = "http://106.ihuyi.com/webservice/sms.php?method=Submit";

    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserInfoMapper userInfoMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    UserCouponMapper userCouponMapper;
    @Autowired
    AmountAccountMapper amountAccountMapper;
    @Autowired
    CommentMapper commentMapper;

    /**
     * 根据所有的待出租车位信息;状态为未出租
     * @param example
     * @return
     */
    @Override
    public Map<String, Object> selectRentParkingInfo(String example) throws Exception{
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, String> parse = Tenant2Utils.parse(example);

        OrdersExample ordersExample = new OrdersExample();
        OrdersExample.Criteria ordersExampleCriteria = ordersExample.createCriteria();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(parse.get("startTime") != null && !parse.get("startTime").equals("")){
            ordersExampleCriteria.andStarttimeGreaterThanOrEqualTo(sdf.parse(parse.get("startTime")));
        }
        if(parse.get("endTime") != null && !parse.get("endTime").equals("")){
            ordersExampleCriteria.andEndtimeLessThanOrEqualTo(sdf.parse(parse.get("endTime")));
        }
        if(parse.get("minPrice") != null && !parse.get("minPrice").equals("")){
            ordersExampleCriteria.andPriceGreaterThanOrEqualTo(Long.valueOf(parse.get("minPrice")));
        }
        if(parse.get("maxPrice") != null && !parse.get("maxPrice").equals("")){
            ordersExampleCriteria.andPriceLessThanOrEqualTo(Long.valueOf(parse.get("maxPrice")));
        }
        Integer pageNum = null;
        if(parse.get("pageNum") != null && !parse.get("pageNum").equals("")){
            pageNum = Integer.parseInt(parse.get("pageNum"));
        }else{
            pageNum = 1;
        }

        Integer pageSize = 8;
        PageHelper.startPage(pageNum,pageSize);
        ordersExampleCriteria.andStatusEqualTo("未出租");
        List<Orders> orders = ordersMapper.selectByExample(ordersExample);

        for(int i = 0 ; i < orders.size() ; i++){
            Integer pid = orders.get(i).getPid();
            List<Comment> comments =  new ArrayList<>();
            comments = lookComments(pid);
            List<Integer> scores = new ArrayList<>();
            if(!comments.isEmpty()){
                for(Comment c :comments){
                    scores.add(c.getScore());
                }
                Double avg = Tenant2Utils.getAvg(scores);
                orders.get(i).getParking().setAvgScore(avg);
            }
        }
        PageInfo<Orders> pageInfo = new PageInfo<>(orders);
        resultMap.put("orders",orders);
        resultMap.put("pageInfo",pageInfo);
        return resultMap;
    }

    /**
     * 修改密码发送短信验证码
     * @param phone
     * @return
     */
    @Override
    public  String  Sendsms(String phone){
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(Url);

        client.getParams().setContentCharset("GBK");
        method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=GBK");

        int mobile_code = (int)((Math.random()*9+1)*100000);

        String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");
        System.out.println(mobile_code);
        NameValuePair[] data = {//提交短信
                new NameValuePair("account", "C96050066"), //查看用户名 登录用户中心->验证码通知短信>产品总览->API接口信息->APIID
                new NameValuePair("password", "eb2b7f65e7172d412e9a69d2ce8d96e0"), //查看密码 登录用户中心->验证码通知短信>产品总览->API接口信息->APIKEY
                //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
                new NameValuePair("mobile", phone),
                new NameValuePair("content", content),
        };
        method.setRequestBody(data);

        try {
            client.executeMethod(method);

            String SubmitResult =method.getResponseBodyAsString();

            //System.out.println(SubmitResult);

            Document doc = DocumentHelper.parseText(SubmitResult);
            Element root = doc.getRootElement();

            String code = root.elementText("code");
            String msg = root.elementText("msg");
            String smsid = root.elementText("smsid");

            System.out.println(code);
            System.out.println(msg);
            System.out.println(smsid);

            if("2".equals(code)){
                System.out.println("短信提交成功");
            }

        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            return mobile_code +"";
        }

    }


    /**
     * 修改用户密码
     * @param user
     */
    @Override
    public void update(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }



    /**
     * 在抢租之前查询租客的情况是否可以进行租赁
     * 检查账户余额充足
     * 检查当前订单是否可以使用代金券
     *
     */
    @Override
    public Map<String,Object> confirmInfo(Integer oid, UserInfo userInfo) {
        Map<String,Object> map = new HashMap<>();
        /**
         * 1.根据订单id查询目标订单，查询到订单的价格
         */
        Orders targetOrder = ordersMapper.selectByPrimaryKey(oid);
        Long price = targetOrder.getPrice();
        userInfo = userInfoMapper.selectByPrimaryKey(userInfo.getUiid());
        BigDecimal balance = userInfo.getBalance();
        int compare = balance.compareTo(new BigDecimal(price + ""));
        /**
         * 2.账户余额小于price则返回 bogo=100
         * 表明账户余额不足
         */
        if(compare == -1){
            map.put("bogo",100);
        }else{
            /**
             * 余额充足 200
             */
            map.put("bogo",200);
        }

        /**
         * 3.查询该用户拥有的优惠劵中是否有达到使用要求的
         */
        /**
         * 第一步，查出满足使用条件的券,抽取出他的cpid
         */
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria couponExampleCriteria = couponExample.createCriteria();
        couponExampleCriteria.andConditionMoneyLessThanOrEqualTo(price);
        List<Coupon> couponList = couponMapper.selectByExample(couponExample);
        List<Integer> cpids = new ArrayList<>();
        for(int i = 0 ; i < couponList.size() ; i++){
            cpids.add(couponList.get(i).getCpid());
        }
        //System.out.println(couponList);
        /**
         * 第二步，查询用户自己拥有的券,其中未使用的券
         */
        UserCouponExample userCouponExample = new UserCouponExample();
        UserCouponExample.Criteria userCouponExampleCriteria = userCouponExample.createCriteria();
        userCouponExampleCriteria.andUiidEqualTo(userInfo.getUiid());
        userCouponExampleCriteria.andUcstatusEqualTo("未使用");
        if(cpids.isEmpty()){
            /**
             * has = 500 表明没有可用代金卷
             */
            map.put("has",500);
        }else{
            /**
             * xxx = 600 表明有可用的代金卷
             */
            userCouponExampleCriteria.andCpidIn(cpids);
            List<UserCoupon> userCouponList = userCouponMapper.selectByExample(userCouponExample);
            map.put("has",600);
            map.put("coupons",userCouponList);
        }

        return map;
    }

    /**
     * 抢租
     * @param order
     * @param uuid
     */
    @Override
    public Integer updateGetParking(Orders order, Integer uuid) {

        try{
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(uuid);
            /**
             * 账户金额小于出租价格返回:100
             */
            if(userInfo.getBalance().compareTo(new BigDecimal(order.getPrice()+"")) == -1){
                return  100;
            }

            /**
             * 1.修改抢租客账户资金状态，减少相应的钱数,若使用了卡券，扣掉的钱减去卡券的钱数
             */
            Long price = order.getPrice();

            if(order.getUcid()== null){
                userInfo.setBalance(userInfo.getBalance().subtract(new BigDecimal(price+"")));
            }else{
                UserCoupon userCoupon =userCouponMapper.selectByPrimaryKey(order.getUcid());
                /**
                 * 如果代金券中的金额 大于 订单中价格
                 * 返回600
                 */

                if(userCoupon.getCoupon().getMoney().compareTo(price) == 1){
                    return 600;
                }
                price = price - userCoupon.getCoupon().getMoney();

                userInfo.setBalance(userInfo.getBalance().subtract(new BigDecimal(price+"")));
            }

            userInfoMapper.updateByPrimaryKeySelective(userInfo);
            //System.out.println(userInfo.getBalance());
            /**
             * 2.增加平台的账户余额，增加钱数
             */
//        /**
//         * 根据角色名查到角色id
//         */
//        RoleExample roleExample = new RoleExample();
//        RoleExample.Criteria roleExampleCriteria = roleExample.createCriteria();
//        roleExampleCriteria.andRnameEqualTo("平台");
//        List<Role> roleList = roleMapper.selectByExample(roleExample);
//        Role role = roleList.get(0);
//
//        /**
//         * 根据角色id，查到 用户 ： 平台 其实平台这个角色只有一个用户
//         */
//        UserRoleExample userRoleExample = new UserRoleExample();
//        UserRoleExample.Criteria userRoleExampleCriteria = userRoleExample.createCriteria();
//        userRoleExampleCriteria.andRidEqualTo(role.getRid());
//        List<UserRoleKey> userRoleKeyList = userRoleMapper.selectByExample(userRoleExample);
//        UserRoleKey userRoleKey = userRoleKeyList.get(0);
//        /**
//         * 根据uid查询到平台的userinfo，增加账户金额
//         */
//        UserInfoExample userInfoExample = new UserInfoExample();
//        UserInfoExample.Criteria userInfoExampleCriteria = userInfoExample.createCriteria();
//        userInfoExampleCriteria.andUidEqualTo(userRoleKey.getUid());
//        List<UserInfo> userInfoList = userInfoMapper.selectByExample(userInfoExample);
//        UserInfo pingtai = userInfoList.get(0);
//        pingtai.setBalance(pingtai.getBalance().add(new BigDecimal(price+"")));
//        userInfoMapper.updateByPrimaryKeySelective(pingtai);
//        System.out.println(pingtai.getBalance());

            /**
             * 将金额加载amount_account的冻结列即可
             */
            List<AmountAccount> amountAccounts = amountAccountMapper.selectByExample(null);
            AmountAccount amountAccount = amountAccounts.get(0);

            amountAccount.setAmountFrozen(amountAccount.getAmountFrozen().add(new BigDecimal(price+"")));
//        System.out.println("PRICE"+price);
//        System.out.println(amountAccount);
            amountAccountMapper.updateByPrimaryKeySelective(amountAccount);
            /**
             * 3.修改订单状态为 "已支付",若使用代金券，将使用过的卡券状态修改为已使用
             */
            UserCoupon userCoupon = new UserCoupon();
            if(order.getUcid() != null){
                userCoupon = userCouponMapper.selectByPrimaryKey(order.getUcid());
                userCoupon.setUcstatus("已使用");
                userCouponMapper.updateByPrimaryKeySelective(userCoupon);
            }
            order.setStatus("已支付");
            order.setPaytime(new Date());
            order.setUiid(userInfo.getUiid());
            ordersMapper.updateByPrimaryKeySelective(order);
            //System.out.println(order);
            /**
             * 一切正常返回200
             */
            return 200;
        }catch (Exception e){
            e.printStackTrace();
            /**
             * 出现bug返回300；
             */
            return 300;
        }
    }

    /**
     * 根据订单id查询订单
     * @param rid
     * @return
     */
    @Override
    public Orders selectOrders(Integer rid) {
        return ordersMapper.selectByPrimaryKey(rid);
    }

    /**
     * 抢租客充值
     * @return
     */
    @Override
    public String top_up(HttpServletRequest req,  HttpServletResponse resp,Map<String,Object> paramMap) throws IOException {
        String result = "";
        try{
            result = Tenant2Utils.doPay(req, resp, paramMap);
        }catch (Exception e){
            result = null;
        }finally {
            return result;
        }
    }

    /**
     * 修改用户账户余额
     * @param uuid
     * @param total_amount
     */
    @Override
    public void updateUserInfoBalance(Integer uuid,String total_amount) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(uuid);
        userInfo.setBalance(userInfo.getBalance().add(new BigDecimal(total_amount)));
        userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }

    /**
     * 查询评论信息
     * @param pid
     * @return
     */
    @Override
    public List<Comment> lookComments(Integer pid) {
        Map<String,Object> map = new HashMap<>();
        CommentExample commentExample = new CommentExample();
        CommentExample.Criteria commentExampleCriteria = commentExample.createCriteria();

        commentExampleCriteria.andStatusEqualTo("审核通过");
        commentExampleCriteria.andPidEqualTo(pid);
        List<Comment> comments = commentMapper.selectByExample(commentExample);


        return comments;
    }
}
